import Router from '@koa/router';
import response from '../response.js';
import { qipiao_get, qipiao_post } from '../qipiao.js';
import db from '../mysqlHelper.js';
import { createToken } from '../auth.js';
import moment from 'moment';

const router = new Router();


async function ticketRecharge(isp_code, ticket_packet_id, value, expire_time,oper_name) {

    if (expire_time == null || expire_time == undefined) {
        expire_time = moment().add(10, 'year').format('YYYY-MM-DD HH:mm:ss');
    }
    let recharge_record = {
        isp_code: isp_code,
        oper_name:oper_name,
        ticket_packet_id: ticket_packet_id,
        recharge_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        oper_type: 1,//人工充值
        expire_time: expire_time,
        value: value
    }
    let change_record = {
        isp_code: isp_code,
        ticket_packet_id: ticket_packet_id,
        change_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        balance: 0,
        change_value: value,
        inventory: value,
        oper_type: 2//充值
    }


    let stock = {
        isp_code: isp_code,
        ticket_packet_id: ticket_packet_id,
        inventory: value,
        creat_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        expire_time: expire_time,
        oper_name:oper_name
    }
    //采用事务写入数据库
    let sqls = [];
    sqls.push({ sql: 'insert into isp_ticket_recharge_record set ?', param: recharge_record });
    sqls.push({ sql: 'insert into isp_ticket_change_record set ?', param: change_record });
    sqls.push({ sql: 'insert into isp_ticket_stock set ?', param: stock });
    let res = await db.transaction(sqls);
    console.log('充值结果', res);
    if (res instanceof Error) {
        return { err: '数据库写入错误:' + res.message };
    }
    return { code: 1 };

}
//服务商优惠券充值接口
router.post('/api/coupon/recharge', async (ctx) => {
    let body = ctx.request.body;
    if (body.isp_code == null || body.isp_code == undefined) {
        ctx.body = response.fail('isp_code不能为空');
        return;
    }
    if (body.ticket_packet_id == null || body.ticket_packet_id == undefined) {
        ctx.body = response.fail('ticket_packet_id不能为空');
        return;
    }
    if (body.value == null || body.value == undefined) {
        ctx.body = response.fail('value不能为空');
        return;
    }
    // console.log('isp 值',JSON.stringify (ctx.state.isp));
    // console.log('oper 值',JSON.stringify (ctx.state.oper));
    let oper_name= ctx.state.oper.name;
    let res = await ticketRecharge(body.isp_code, body.ticket_packet_id, body.value, body.expire_time,oper_name);
    console.log('充值返回', res);
    if (res.err) {
        ctx.body = response.fail(res.err);
        return;
    }
    ctx.body = response.success('充值成功');

});


export { router };
